package com.situ.allaia.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.allaia.dao.AdminUserDao;
import com.situ.allaia.model.AdminUser;
import com.situ.allaia.model.AdminUserSearchBean;
import com.situ.allaia.service.AdminUserService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminUserServiceImp implements AdminUserService {
    private  AdminUserDao adminUserDao;

    public AdminUserServiceImp(AdminUserDao adminUserDao) {
        this.adminUserDao = adminUserDao;
    }

    @Override
    public AdminUser findByUsername(String username) {
        return adminUserDao.findByUsername(username);
    }

    @Override
    public List<AdminUser> findAll(AdminUserSearchBean asb, PaginateInfo pi) {
        PageHelper.startPage(pi.getPageNo(),pi.getPageSize());
        List<AdminUser> result = adminUserDao.findAll(asb);
        //获取分页数据
        PageInfo<AdminUser> p = new PageInfo<>(result);
        pi.setTotal(p.getTotal());
        return result;
    }

    @Override
    public boolean save(AdminUser adminUser) {
        adminUser.setCreateTime(LocalDateTime.now());
        adminUser.setLastModifyTime(LocalDateTime.now());

        String encrypt = adminUser.getPassword() + "{"+adminUser.getUsername()+"}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes(StandardCharsets.UTF_8));
        adminUser.setPassword(encrypt);
        System.out.println(adminUser);
        return adminUserDao.save(adminUser)>0;
    }


    @Override
    public AdminUser findById(Integer id) {
        return adminUserDao.findById(id);
    }

    @Override
    public boolean update(AdminUser adminUser) {
        String encrypt = adminUser.getPassword() + "{" + adminUser.getUsername() + "}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes(StandardCharsets.UTF_8));
        adminUser.setLastModifyTime(LocalDateTime.now());
        adminUser.setPassword(encrypt);
        return adminUserDao.update(adminUser) > 0;
    }


    @Override
    public int deleteByIds(Integer[] ids) {
        return adminUserDao.deleteByIds(ids);
    }
}
